//
//  WBStatusListViewModel.swift
//  Swift_sina
//
//  Created by TFB_WGP on 2017/9/1.
//  Copyright © 2017年 TFB_WGP. All rights reserved.
//

import Foundation

/// 微博数据列表视图模型
//如果一个类只是包装了一些代码逻辑,可以不用父类,更轻量级

private let maxPullUpTryTimes = 3

class WBStatusViewModel {
    
    /// 微博数据列表数组
    lazy var statusList = [WBStatus]()
    /// 上拉刷新错误次数
    fileprivate var pullupErrorTimes = 0;
    
    func loadStatus(pullup: Bool, completion: @escaping (_ isSuccess:Bool, _ shouldRefresh: Bool)->()) {
        
        if pullup && pullupErrorTimes > maxPullUpTryTimes {
            completion(true, false)
            return
        }
//        下拉刷新
        let since_id = pullup ? 0 : (statusList.first?.id ?? 0)
        /// 上拉刷新
        let max_id = !pullup ? 0 : (statusList.last?.id ?? 0)
    
        NetworkRequest.sharedInstance.statusList(since_id:since_id, max_id:max_id) { (json, error) in
            
//            字典转模型
            guard let js = json,let array = NSArray.yy_modelArray(with: WBStatus.self, json: js) as? [WBStatus] else{
                
                completion(false,false)
                return
            }
            WPPrint(items: "刷新了\(array.count)条数据")
//            拼接数据:下拉刷新
            if pullup {
                self.statusList += array;
            }
            else {
                self.statusList = array + self.statusList
            }
            
            if pullup && array.count == 0 {
                self.pullupErrorTimes += 1
                completion(true, false)
            }
            else if array.count == 0{
                //3.完成回调
                completion(true,false)
            }
            else
            {
                completion(true,true)
            }
        }
    }
}
